// Initial position
var fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
var move = "";
var playing = false;
var color = "";
var selected = "";

var statTime = 3000;
var lastresp = "";
var lastmove = "";
var flipped = false;

var numbers = "12345678";

var imgpath = '/img/fantasy_shad/';

// Update the chessboard based on the FEN
function updateBoard() {
  var pos = fen.split(' ')[0];
  var rows = pos.split('/');
  var crow = $("#chessboard-area table tr:first");
  var tmp;
  var n;
  if (flipped) {
    for (var i = 7; i >= 0; i--) {
      var tmp = "";
      for (var j = 0; j < rows[i].length; j++)
        tmp = rows[i][j] + tmp;
      updateRow(crow, tmp);
      crow = crow.next();
    }
  }
  else {
    for (var i = 0; i < 8; i++) {
      updateRow(crow, rows[i]);
      crow = crow.next();
    }
  }
}

// Update a row
function updateRow(row, str) {
  var cells = row.children();
  var p = 0;
  var i = 0;
  var img = "";
  while (i < 8) {
    if (numbers.indexOf(str[p]) >= 0) {
      sk = parseInt(str[p]);
      for (var j = 0; j < sk; j++) {
        cells[i].innerHTML = "";
        cells[i].abbr = "";
        
        i++;
      }
    }
    else {
      if (cells[i].abbr != str[p]) {
        
        cells[i].abbr = str[p];
  
        img = "";
        
        if (str[p] < 'z' && str[p] > 'a') img = "b";
        else img = "w";
        
        img += str[p].toLowerCase();
      
        img = imgpath + img + ".png";
        img = '<img src="' + img + '" width="40" height="40" />';
        cells[i].innerHTML = img;
        
      }
      i++;
    }
      
    p++;
  }
}

function sendMove() {
  $.ajax({
    url: '/game/' + roomid,
    type: 'POST',
    data: {move: move},
    success: function(data, textStatus) {
      if (data.substr(0, 3) == "Err") {
        notify(data.substr(5));
      }
      else {
        fen = data.substr(3);
        updateBoard();
      }
    }
  });
  $(selected).removeClass("selected");
  move = "";
}

// Process when clicking a square
function squareClicked(sq) {
  if (!playing) return;
  if (move == "") {
    if (sq.innerHTML != "") {
      move = sq.abbr.toUpperCase() + sq.id;
      selected = sq;
      $(sq).addClass("selected");
    }
  }
  else if (sq.id == selected.id){
    // Cancel the move
    $(sq).removeClass("selected");
    move = "";
  }
  else {
    // Submit the move
    move = move + "-" + sq.id;
    if (move[0] == "P" && (sq.id[1] == "8" || sq.id[1] == "1")) {
      // Promotion move
      $("#promotion").fadeIn("slow");      
    }
    else {
      sendMove();
    }
  }
}

function promote(piece) {
  move = move + "=" + piece;
  sendMove();
  $("#promotion").fadeOut("slow");
}

$(document).ready(function() {
  // Update board
  updateBoard();
  
  // Add click listener to all squares
  $("td.square").click(function() {
    squareClicked(this);
  });
  
  getStatus();
});

function sendCommand(comm, success) {
  $.ajax({
    url: '/game/comm/' + roomid,
    type: 'POST',
    data: {command: comm},
    success: function(data, textStatus) {
      if (data.substr(0, 2) == "OK") {
        success(data, textStatus);
      }
      else {
        notify(data.substr(5));
      }
    }
  })
}

function chooseColor(col) {
  if (color != "") {
    alert("Already chosen color");
    return;
  }
  sendCommand(col, function(data, textStatus) {
    $("#" + col + "-player").html(data.substr(4));
    color = col[0];
  });
}

function chooseBlack() {
  chooseColor("black");
}

function chooseWhite() {
  chooseColor("white");
}

function Ready() {
  sendCommand('ready', function(data, textStatus) {});
}

function getStatus() {
  $.ajax({
    url: '/game/' + roomid,
    type: 'GET',
    success: function(data, textStatus) {
      if (data != lastresp) {
        lastresp = data;
        
        var res = data.split('|');
        
        updateStatus(res);
      }
      setTimeout("getStatus()", statTime);
    }
  });
}

function updateLastMove(lmove) {
  var move;
  if (lastmove.length == 5) {
    move = lastmove.split("-");
    $("#" + move[0]).removeClass("lastmove");
    $("#" + move[1]).removeClass("lastmove");
  }
  lastmove = lmove;

  if (lastmove == "") return;
  
  move = lastmove.split("-");
  $("#" + move[0]).addClass("lastmove");
  $("#" + move[1]).addClass("lastmove");
}

function updateStatus(data) {
  $("#white-player").html(data[1]);
  $("#black-player").html(data[2]);
  
  if (data[0] == 'waiting') {
    // waiting|white|black|color
    color = data[3];
    if (fen != "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") {
      fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
      updateBoard();
      updateLastMove("");
    }
  }
  else if (data[0] == 'playing') {
    // playing|white|black|fen|color
    fendata = data[3].split(' ');
    color = data[4];
    playing = (fendata[1] == color);
    if (fen != data[3]) {
      fen = data[3];
      updateBoard()
    }
    updateLastMove(data[5]);
  }
  else if (data[0] == "finished") {
    // finished|white|black|fen|result
    if (fen != data[3]) {
      fen = data[3];
      updateBoard();
    }
    notify(data[4].split("/")[1]);
  }

  updateCommand(data);
}

function ncolor() {
  sendCommand('ncolor', function(data, textStatus) {});
}

function newGame() {
  sendCommand('new', function(data, textStatus) {
    fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
    updateBoard();
    updateLastMove("");
  });
}

function resign() {
  sendCommand('resign', function(data, textStatus) {});
}

function notify(msg) {
  $("#message").html(msg);
  $("#notifications").fadeIn("slow");
}

function hideNotify() {
  $("#notifications").fadeOut("slow");
}

function showCommand(commands) {
  $("#commands a").css("display", "none");
  for (i in commands) {
    $(commands[i]).css("display", "block");
  }
}

function updateCommand(data) {
  if (data[0] == "waiting") {
    // No color yet
    if (color == "")
      showCommand(new Array("a#cmdBlack", "a#cmdWhite"));
    else
      showCommand(new Array("a#cmdReady", "a#cmdNColor"));
  }
  else if (data[0] == "playing") {
    showCommand(new Array("a#cmdResign"));
  }
  else if (data[0] == "finished") {
    showCommand(new Array("a#cmdNewGame"));
  }
}

function flipBoard() {
  // Replace id of all cells
  $("table.chessboard td.square").each(function() {
    this.id = oppositeCol(this.id[0]) + oppositeRow(this.id[1]);
  });
  flipped = !flipped;
  updateBoard();
  
  // Update last move
  $("td.lastmove").removeClass("lastmove");
  updateLastMove(lastmove);
  
  // Replace rowid and colid
  $("table.chessboard td.colid").each(function() {
    this.innerHTML = oppositeCol(this.innerHTML);
  });
  $("table.chessboard td.rowid").each(function() {
    this.innerHTML = oppositeRow(this.innerHTML);
  });
  
  // Swap the div contains player name
  var black = $("#black-player")[0];
  var white = $("#white-player")[0];
  black.id = "white-player";
  white.id = "black-player";
  var tmp = white.innerHTML;
  white.innerHTML = black.innerHTML;
  black.innerHTML = tmp;
}

function oppositeCol(col) {
  switch (col) {
    case 'a': return 'h';
    case 'b': return 'g';
    case 'c': return 'f';
    case 'd': return 'e';
    case 'e': return 'd';
    case 'f': return 'c';
    case 'g': return 'b';
    case 'h': return 'a';
  }
}

function oppositeRow(row) {
  var r = parseInt(row);
  return 9 - row;
}